package com.kate.mall.bff.wx.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.kate.mall.bff.wx.controller.form.CartAddForm;
import com.kate.mall.bff.wx.dto.CartDTO;
import com.kate.mall.bff.wx.feign.OrderFeignClient;
import com.kate.mall.bff.wx.feign.ProductFeignClient;
import com.kate.mall.common.utils.ListMap2ListVoUtils;
import com.kate.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.kate.mall.common.constants.WxResponseCode.GOODS_NO_STOCK;
import static com.kate.mall.common.constants.WxResponseCode.GOODS_UNSHELVE;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2021/8/17 17:42
 */
@Service
@Slf4j
public class CartService {
    @Resource
    private ProductFeignClient goodsFeignClient;

    @Resource
    private OrderFeignClient cartFeignClient;

    public R save(Integer userId, CartAddForm cartAddForm) {
        if(userId==null||userId<=0){
            return  R.unlogin();
        }
        if (cartAddForm == null) {
            return R.badArgument();
        }

        Integer productId = cartAddForm.getProductId();
        Integer number = cartAddForm.getNumber().intValue();
        Integer goodsId = cartAddForm.getGoodsId();
        //hutool工具类 ObjectUtil
        if (!ObjectUtil.isAllNotEmpty(productId, number, goodsId)) {
            return R.badArgument();
        }
        if (number <= 0) {
            return R.badArgument();
        }

        //判断商品是否可以购买
        R goodsR = goodsFeignClient.detail(goodsId);

        if (goodsR == null ||
                !ObjectUtil.equal(Convert.convert(Integer.class, ((Map) goodsR.get("goods")).get("isOnSale")), new Integer(1))) {
            return R.error(GOODS_UNSHELVE.getCode(), "商品已下架");
        }

        R productR = goodsFeignClient.findProductById(productId);
        //判断购物车中是否存在此规格商品
        R existCartR = cartFeignClient.queryExist(goodsId, productId, MapUtil.get(MapUtil.get(productR, "goodsProduct", Map.class), "price", BigDecimal.class), userId);
        List<Map> existCartMap = MapUtil.get((Map) existCartR.get("page"), "list", List.class);
        List<CartDTO> cartDtoList = ListMap2ListVoUtils.entity2Vo(existCartMap, CartDTO.class);
        CartDTO existCart = cartDtoList.size() == 0 ? null : cartDtoList.get(0);
        Integer newCartId = null;
        if (existCart == null) {
            //取得规格的信息,判断规格库存
            if (productR == null || number > Convert.convert(Integer.class, MapUtil.get((Map) productR.get("goodsProduct"),
                    "number", Integer.class))) {// product.getNumber()) {
                return R.error(GOODS_NO_STOCK.getCode(), "库存不足");
            }


            cartAddForm.setId(null);
            cartAddForm.setGoodsSn(MapUtil.get((Map) goodsR.get("goods"), "goodsSn", String.class));
            cartAddForm.setGoodsName(MapUtil.get((Map) goodsR.get("goods"), "name", String.class));
            if (StrUtil.isNotEmpty(MapUtil.get((Map) goodsR.get("goods"), "picUrl", String.class))) {
                cartAddForm.setPicUrl(MapUtil.get((Map) goodsR.get("goods"), "picUrl", String.class));
            } else {
                cartAddForm.setPicUrl(MapUtil.get((Map) productR.get("goodsProduct"), "url", String.class));
            }
            cartAddForm.setPrice(MapUtil.get((Map) productR.get("goodsProduct"), "price", BigDecimal.class));
            //specifications----->specifications[]
            //String specificationsStr = MapUtil.get((Map) productR.get("goodsProduct"), "specification", String.class);
            //String[] specifications = JSONUtil.parseArray(specificationsStr).toArray(new String[]{});
            cartAddForm.setSpecifications(MapUtil.get((Map) productR.get("goodsProduct"), "specifications", String[].class));
            cartAddForm.setUserId(userId);
            cartAddForm.setChecked(true);
            newCartId = MapUtil.get(cartFeignClient.add(cartAddForm), "data", Integer.class);
        } else {
            //取得规格的信息,判断规格库存
            int num = number;
            if (num > MapUtil.get((Map) productR.get("goodsProduct"), "number", Integer.class)) {
                return R.error(GOODS_NO_STOCK.getCode(), "库存不足");
            }

            existCart.setNumber(num);
            BeanUtil.copyProperties(existCart,cartAddForm,false);
            //字符串数组转字符串
            //String[] specificationsArray = existCart.getSpecifications();
            //JSONArray array = JSONUtil.createArray();
            //for (String s : specificationsArray) {
            //    array.add(s);
            //}
            //cartAddForm.setSpecifications(array.toString());
            if (!MapUtil.get(cartFeignClient.updateById(cartAddForm), "data", Boolean.class)) {
                return R.updatedDataFailed();
            }
        }
        return  R.ok().put("data", newCartId != null ? newCartId : existCart.getId());
    }

    public void updateCheck(Integer userId, List<Integer> productIds, Boolean isChecked) {
    }

    public List<CartDTO> queryByUid(Integer userId) {
       R cartListR =  cartFeignClient.queryByUId(userId);
        List<Map> list = MapUtil.get((Map) cartListR.get("page"), "list", List.class);
        List<CartDTO> cartDtoList = ListUtil.list(false);
        list.forEach(map->{
            cartDtoList.add(new CartDTO()
                    .setGoodsId(MapUtil.get(map,"goodsId",Integer.class))
                    .setId(MapUtil.get(map,"id",Integer.class))
                    .setProductId(MapUtil.get(map,"productId",Integer.class))
                    .setNumber(MapUtil.get(map,"productId",Integer.class)));
        });
        return cartDtoList;
    }

    public void deleteById(Integer id) {
        cartFeignClient.deleteById(new Integer[]{id});
    }


    public CartDTO findById(Integer cartId) {
       R cartR = cartFeignClient.findCartById(cartId);
       CartDTO cartDto= MapUtil.get(cartR,"cart", CartDTO.class);
       //specifications:string----jsonarray
       cartDto.setSpecifications(JSONUtil.parseArray(MapUtil.get((Map)cartR.get("cart"),"specifications",String.class)).toArray(new String[]{}));
       return cartDto;
    }
}
